using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using System;
using UnityEngine;
using UnityEngine.UI;
using LuaInterface;
using Vuplex.WebView;

public class WebViewEx : MonoBehaviour
{
    Vuplex.WebView.CanvasWebViewPrefab browser;

    public GameObject[] data_arr;

    public RectTransform close_rect;

    // 1用来传入url


    // Start is called before the first frame update
    void Start()
    {

      //  SetBtnPos(0, 0);

    }



    public async void LoadUrl(string url)
    {

        browser = GetComponent<Vuplex.WebView.CanvasWebViewPrefab>();
        await Task.WhenAll(new Task[] {
               browser.WaitUntilInitialized()
            });

        browser.WebView.LoadUrl(url);
        // Web.ClearAllData();//清理缓存
        // Web.SetIgnoreCertificateErrors(true);//证书错误忽略

        browser = GetComponent<Vuplex.WebView.CanvasWebViewPrefab>();
        browser.WebView.UrlChanged += (sender, eventArgs) =>
        {
            data_arr[0].gameObject.name = eventArgs.Url;
            Debug.Log("[CanvasWebViewDemo] URL changed: " + eventArgs.Url);
            urlChanged();
        };
    }

    public async void LoadHtml(string htmlContent)
    {
        LoadTestAAHtml();
       //try
        // {
        //     browser = GetComponent<Vuplex.WebView.CanvasWebViewPrefab>();
        //     await Task.WhenAll(new Task[] {
        //         browser.WaitUntilInitialized()
        //     });

        //     browser.WebView.LoadHtml(htmlContent);
        //     Debug.Log("[WebViewEx] HTML内容加载成功");
        // }
        // catch (System.Exception e)
        // {
        //     Debug.LogError("[WebViewEx] 加载HTML失败: " + e.Message);
        // }
    }

    public async void LoadTestAAHtml()
    {
        try
        {
            Debug.Log("[WebViewEx] 开始加载testAA.html文件...");
            
            browser = GetComponent<Vuplex.WebView.CanvasWebViewPrefab>();
            if (browser == null)
            {
                Debug.LogError("[WebViewEx] 未找到CanvasWebViewPrefab组件");
                return;
            }
            
            Debug.Log("[WebViewEx] 等待WebView初始化...");
            await Task.WhenAll(new Task[] {
                browser.WaitUntilInitialized()
            });
            Debug.Log("[WebViewEx] WebView初始化完成");

            // 加载res目录下的testAA.html文件
            string htmlPath = "testAA";
            Debug.Log("[WebViewEx] 尝试加载资源: " + htmlPath);
            TextAsset htmlAsset = Resources.Load<TextAsset>(htmlPath);
            
            if (htmlAsset != null)
            {
                Debug.Log("[WebViewEx] 成功加载HTML文件，内容长度: " + htmlAsset.text.Length);
                Debug.Log("[WebViewEx] HTML内容前100字符: " + htmlAsset.text.Substring(0, Math.Min(100, htmlAsset.text.Length)));
                
                // 检查是否是Base64编码的内容
                string htmlContent = htmlAsset.text;
                if (htmlContent.StartsWith("PCFET0NUWVBFIGh0bWw+") && htmlContent.Length > 1000)
                {
                    Debug.Log("[WebViewEx] 检测到可能的Base64编码的HTML内容，尝试解码...");
                    try
                    {
                        // 检查是否真的是Base64编码（只包含Base64字符）
                        bool isBase64 = true;
                        foreach (char c in htmlContent)
                        {
                            if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '+' || c == '/' || c == '='))
                            {
                                isBase64 = false;
                                break;
                            }
                        }
                        
                        if (isBase64)
                        {
                            byte[] bytes = Convert.FromBase64String(htmlContent);
                            htmlContent = System.Text.Encoding.UTF8.GetString(bytes);
                            Debug.Log("[WebViewEx] Base64解码成功，解码后内容长度: " + htmlContent.Length);
                        }
                        else
                        {
                            Debug.Log("[WebViewEx] 内容不是Base64编码，使用原始内容");
                        }
                    }
                    catch (Exception decodeEx)
                    {
                        Debug.LogWarning("[WebViewEx] Base64解码失败，使用原始内容: " + decodeEx.Message);
                    }
                }
                else
                {
                    Debug.Log("[WebViewEx] 使用原始HTML内容");
                }
                
                // 添加WebView事件监听
                browser.WebView.LoadProgressChanged += (sender, eventArgs) =>
                {
                    Debug.Log("[WebViewEx] 加载进度: " + eventArgs.Progress);
                };
                
                browser.WebView.UrlChanged += (sender, eventArgs) =>
                {
                    Debug.Log("[WebViewEx] URL改变: " + eventArgs.Url);
                };
                
                // 记录HTML内容的基本信息
                Debug.Log("[WebViewEx] HTML内容分析:");
                Debug.Log("[WebViewEx] - 内容长度: " + htmlContent.Length);
                Debug.Log("[WebViewEx] - 包含JavaScript: " + htmlContent.Contains("<script"));
                Debug.Log("[WebViewEx] - 包含CSS: " + htmlContent.Contains("<style"));
                Debug.Log("[WebViewEx] - 包含外部资源: " + htmlContent.Contains("http"));
                
                // 尝试通过JavaScript注入来改善兼容性
                try
                {
                    // 注入一些JavaScript来模拟桌面浏览器环境
                    string compatibilityScript = @"
                        // 模拟桌面浏览器环境
                        if (typeof navigator !== 'undefined') {
                            navigator.userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36';
                        }
                        console.log('WebView兼容性脚本已注入');
                    ";
                    
                    browser.WebView.ExecuteJavaScript(compatibilityScript);
                    Debug.Log("[WebViewEx] 兼容性脚本注入完成");
                }
                catch (System.Exception scriptEx)
                {
                    Debug.LogWarning("[WebViewEx] 兼容性脚本注入失败: " + scriptEx.Message);
                }
                
                browser.WebView.LoadHtml(htmlContent);
                Debug.Log("[WebViewEx] LoadHtml调用完成");
                
                // 延迟检查WebView状态
                StartCoroutine(CheckWebViewStatus());
            }
            else
            {
                Debug.LogError("[WebViewEx] 未找到testAA.html文件，请确保文件位于Resources/目录下");
            }
        }
        catch (System.Exception e)
        {
            Debug.LogError("[WebViewEx] 加载HTML失败: " + e.Message);
            Debug.LogError("[WebViewEx] 异常堆栈: " + e.StackTrace);
        }
    }

    public async void LoadHtmlFromJson(string jsonResponse)
    {
        try
        {
            // 解析JSON响应中的HTML内容
            string htmlContent = ParseHtmlFromJson(jsonResponse);
            if (!string.IsNullOrEmpty(htmlContent))
            {
                LoadHtml(htmlContent);
            }
            else
            {
                Debug.LogWarning("[WebViewEx] JSON响应中未找到HTML内容");
            }
        }
        catch (System.Exception e)
        {
            Debug.LogError("[WebViewEx] 解析JSON失败: " + e.Message);
        }
    }

    private string ParseHtmlFromJson(string jsonResponse)
    {
        try
        {
            // 简单的JSON解析，提取html字段
            if (jsonResponse.Contains("\"html\":"))
            {
                int startIndex = jsonResponse.IndexOf("\"html\":\"") + 8;
                int endIndex = jsonResponse.IndexOf("\"", startIndex);
                
                if (startIndex > 7 && endIndex > startIndex)
                {
                    string htmlContent = jsonResponse.Substring(startIndex, endIndex - startIndex);
                    // 解码转义字符
                    htmlContent = htmlContent.Replace("\\\"", "\"")
                                           .Replace("\\n", "\n")
                                           .Replace("\\t", "\t")
                                           .Replace("\\/", "/");
                    return htmlContent;
                }
            }
            return null;
        }
        catch
        {
            return null;
        }
    }

    public void SetAudioMuted(bool muted)
    {
        var mutableWebView = browser.WebView as Vuplex.WebView.IWithMutableAudio;
        if (mutableWebView != null)
        {
            mutableWebView.SetAudioMuted(muted);
        }
    }

    public void ReturnHall()
    {
  
        if (LuaMgr.GetMainState() != null)
        {
            LuaFunction func = LuaMgr.GetMainState().GetFunction("ScriptToLua.ScriptToLua.returnHall");
            if (func != null)
            {
                func.BeginPCall();
                func.PCall();
                func.EndPCall();
                func.Dispose();
            }
        }
    }

    public void SetBtnPos(string s)
    {
        // 用_切割字符串
        string[] values = s.Split('_');
        
        // 尝试将字符串转换为float
        close_rect.anchorMin = new Vector2(float.Parse(values[0]), float.Parse(values[1]));
        close_rect.anchorMax = new Vector2(float.Parse(values[2]), float.Parse(values[3]));
        close_rect.pivot = new Vector2(float.Parse(values[4]), float.Parse(values[5]));
        close_rect.localEulerAngles = new Vector3(float.Parse(values[6]), float.Parse(values[7]), float.Parse(values[8]));
        close_rect.anchoredPosition = new Vector2(float.Parse(values[9]), float.Parse(values[10]));
       
    }
    public void urlChanged()
    {
        if (LuaMgr.GetMainState() != null)
        {
            LuaFunction func = LuaMgr.GetMainState().GetFunction("ScriptToLua.ScriptToLua.urlChanged");
            if (func != null)
            {
                func.BeginPCall();
                func.PCall();
                func.EndPCall();
                func.Dispose();
            }
        }
    }

    private System.Collections.IEnumerator CheckWebViewStatus()
    {
        yield return new WaitForSeconds(2f); // 等待2秒
        
        if (browser != null && browser.WebView != null)
        {
            Debug.Log("[WebViewEx] WebView组件状态检查:");
            Debug.Log("[WebViewEx] - WebView是否为空: " + (browser.WebView == null));
            Debug.Log("[WebViewEx] - WebView是否可见: " + browser.gameObject.activeInHierarchy);
            Debug.Log("[WebViewEx] - WebView RectTransform: " + browser.GetComponent<RectTransform>());
            
            // 尝试获取当前URL
            try
            {
                string currentUrl = browser.WebView.Url;
                Debug.Log("[WebViewEx] - 当前URL: " + currentUrl);
            }
            catch (System.Exception e)
            {
                Debug.LogWarning("[WebViewEx] - 获取URL失败: " + e.Message);
            }
        }
        else
        {
            Debug.LogError("[WebViewEx] WebView组件为空");
        }
    }

}
